package com.orange.fastdfs.controller;

import com.orange.fastdfs.modle.FileSystem;
import com.orange.fastdfs.pojo.Result;
import lombok.extern.slf4j.Slf4j;
import org.csource.common.NameValuePair;
import org.csource.fastdfs.*;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.*;
import java.util.Arrays;
import java.util.List;
import java.util.UUID;

@Slf4j
@RestController
@RequestMapping("/filesystem")
public class FileServerController {

    // Arrays.asList可以将任意数据封装为集合(这里将文件的后缀分装为一个集合方便在文件上传时候进行校验)
    private static final List<String> ALLOW_TYPES = Arrays.asList("image/jpeg", "image/png", "image/jpg");

    @Value("${orange-fastdfs.upload_location}")
    private String upload_location;

    @PostMapping("/uploadFile")
    @ResponseBody
    public Result upload(@RequestParam("file") MultipartFile file) throws IOException {
        //将文件先存储在web服务器上(本机),在调用fastDFS的client将文件上传到 fastDFS服务器
        FileSystem fileSystem = new FileSystem();

        String contentType = file.getContentType();
        //检验当前文件是否在上述集合中
        log.info("上传的文件类型为：{}", contentType);
        if (!ALLOW_TYPES.contains(contentType)) {
            return Result.error("不支持此文件类型上传 : " + contentType);
        }

        //文件原始名称
        String originalFilename = file.getOriginalFilename();

        //文件扩展名比如22.jpg
        String extension = originalFilename.substring(originalFilename.lastIndexOf("."));
        log.info("文件扩展名后缀 = {}", extension);//.jpg
        String filenameExtension = StringUtils.getFilenameExtension(originalFilename);
        log.info("文件类型 = {}", filenameExtension);//jpg
        if (filenameExtension == null) {
            return Result.error("此文件没有文件扩展名");
        }

        //新文件名称
        String fileName = UUID.randomUUID().toString().replace("-", "") + "." + filenameExtension;
        log.info("新文件名称 = {}", fileName);

        //定义file,使用file存储上传的文件
        //File file1 = new File("D:\\image\\upload\\" + fileName);
        File file1 = new File(upload_location + fileName);
        //指定照片上传路径,上传的文件写入到新的文件
        file.transferTo(file1);
        //获取新上传文件的物理路径
        String newFilePath = file1.getAbsolutePath();

        //通过fastDSF的client代码访问tracker和storage
        try {
            //加载fastDFS客户端的配置 文件
            ClientGlobal.initByProperties("config/fastdfs-client.properties");
            System.out.println("network_timeout=" + ClientGlobal.g_network_timeout + "ms");
            System.out.println("charset=" + ClientGlobal.g_charset);

            //创建tracker的客户端
            TrackerClient trackerClient = new TrackerClient(ClientGlobal.getG_tracker_group());
            //通过TrackerClient对象获取TrackerServer信息
            TrackerServer trackerServer = trackerClient.getTrackerServer();
            StorageServer storageServer = null;

            //定义storage的客户端,建立与Storage服务器的连接
            StorageClient1 storageClient = new StorageClient1(trackerServer, storageServer);

            //文件元信息
            NameValuePair[] metaList = new NameValuePair[1];
            metaList[0] = new NameValuePair("fileName", "52.png");

            //执行上传
            String fileId = storageClient.upload_file1(newFilePath, filenameExtension, metaList);
            System.out.println("upload success. file id is: " + fileId);
            fileSystem.setFileId(fileId);
            fileSystem.setFilePath(fileId);
            fileSystem.setFileName(originalFilename);
            fileSystem.setFileSize(file.getSize());
            fileSystem.setFileType(contentType);
            //通过调用service及dao将文件的路径存储到数据库中

            //关闭storage客户端
            storageClient.close();
        } catch (Exception e) {
            log.error("上传文件失败：", e);
            e.printStackTrace();
        }

        return Result.success(fileSystem);
    }
}
